# -*- coding: utf-8 -*-
import json
import time

import requests
import retrying as retrying


class HTTP(object):
    """
        requests模块封装使用：
        import HTTP
        # post调用时格式为json格式
        headers = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
        }
        result = HTTP.get(url, params)
        result = HTTP.post(url, data=json.dumps(payload), headers=header)
        """

    @staticmethod
    def __requests(method, url, **kwargs):
        """
        发送http请求
        @param url: 接口url
        @param method: http请求方法
        @param kwargs: 接受request原生的关键字参数
        @return 响应对象
        """
        resp = getattr(requests, method)(url, **kwargs)
        if resp.status_code == 200:
            result = resp.json()
            return result
        raise Exception('fail:{},url:{},method:{}'.format(json.dumps(resp.content), url, method))

    @classmethod
    @retrying.retry(stop_max_attempt_number=3)
    def get(cls, url, params=None, **kwargs):
        return cls.__requests('get', url, params=params, **kwargs)

    @classmethod
    @retrying.retry(stop_max_attempt_number=3)
    def post(cls, url, data, **kwargs):
        return cls.__requests('post', url, data=data, **kwargs)

    @classmethod
    @retrying.retry(stop_max_attempt_number=3)
    def put(cls, url, data=None, **kwargs):
        return cls.__requests('put', url, data=data, **kwargs)

    @classmethod
    @retrying.retry(stop_max_attempt_number=3)
    def delete(cls, url, **kwargs):
        return cls.__requests('delete', url, **kwargs)

    @classmethod
    @retrying.retry(stop_max_attempt_number=3)
    def head(cls, url, **kwargs):
        return cls.__requests('head', url, **kwargs)

    @classmethod
    @retrying.retry(stop_max_attempt_number=3)
    def patch(cls, url, data=None, **kwargs):
        return cls.__requests('patch', url, data=data, **kwargs)


if __name__ == '__main__':
    print("Python")
    urls = [
        "https://jsonplaceholder.typicode.com/posts/3",
        "https://jsonplaceholder.typicode.com/posts",
        "https://jsonplaceholder.typicode.com/posts?userId=2",
        "https://jsonplaceholder.typicode.com/photos"
    ]
    for url in urls:
        res = HTTP.get(url)
        print(res)
        time.sleep(1)
